package com.zzyweb.managementsystem.token;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zzyweb.managementsystem.pojo.UserInfo;
import org.springframework.stereotype.Component;


import java.util.Date;

/**
 * @author zhiyi
 * @date 9/22/25
 **/
@Component
public class MyJWTUtil {
    private static final String SECRET_KEY = "mySecretKey";
    private static final String ISSUER = "issuer";
    private static final Long EXPIRATION = (long) (1000 * 60 * 60);
    private static final Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY.getBytes());

    public static String createToken(UserInfo userInfo) {
        /*Map<String, Object> claims = new HashMap<>();
        claims.put("username", user.getUsername());
        claims.put("userId", user.getId());
        claims.put("type",user.getType());*/
        Date now = new Date();
        String token = JWT.create().withIssuer(ISSUER)
                .withExpiresAt(new Date(now.getTime() + EXPIRATION))
                .withClaim("username", userInfo.getUsername())
                .withClaim("userId", userInfo.getId())
                .sign(algorithm);
        return token;
    }

    public static TokenState verify(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(algorithm).build();
            //通过调用verify这个函数 ，会验证head payloader 以及signature expiration  以及其他规则 如果有问题抛出如下两个异常
            DecodedJWT verify = jwtVerifier.verify(token);
            return TokenState.VALIDTOKEN;
        }  catch (TokenExpiredException e) {
            return TokenState.EXPIREDTOKEN;
        } catch (JWTVerificationException e) {
            return TokenState.VALIDTOKEN;
        }
    }
}
